<?php

require_once dirname(__FILE__) . '/../lib/BaselzauthActions.class.php';

/**
 * lzlogin actions.
 * 
 * @package    sfLoginzaPropelPlugin
 * @subpackage lzauth
 * @author     Chudov Roman
 * @version    SVN: $Id: actions.class.php 12534 2008-11-01 13:38:27Z Kris.Wallsmith $
 */
class lzauthActions extends BaselzauthActions {

    public function executeLogin(sfWebRequest $request) {
        /* if this is redirection from loginza with POST method,
         * then do authtorizing of user
         */
        echo $request->getHost();
        if ($request->isMethod('post')) {
            //get authtorization info by token, returned in POST parameter
            $url = sfConfig::get('app_LoginzaPlugin_loginza_auth_info') . '?token=' . $request->getParameter('token');
            $this->loginza_response = json_decode(file_get_contents($url), true);

            if (isset($this->loginza_response['error_type'])) {
                echo '<script>alert("Authtorization error!");</script>';
                return;
            }

            $this->user = $this->getUser();
            $criteria = new Criteria();

            $identity = $this->loginza_response['identity'];
            $criteria->add(LzUserProviderPeer::IDENTITY, $identity, Criteria::EQUAL);
            $user_provider_from_db = LzUserProviderPeer::doSelectOne($criteria);

            /*
             * if no such user_provider, then create new user and new user_provider
             */
            if (!$user_provider_from_db) {
                // creating new user_provider
                $user_provider_from_db = $this->createUserProvider();

                //set properties for new user
                $new_user = new LzUser();
                $new_user->setExpiresAt($this->getExpiresAtTime());
                $new_user->setIdUserProvider($user_provider_from_db->getId());
                $new_user->save();

                //create new internal_external_ids's record for new user and new user_provider
                $in_ex = new LzInternalExternalIds();
                $in_ex->setIdInternal($new_user->getId());
                $in_ex->setIdExternal($user_provider_from_db->getId());
                $in_ex->save();

                // set ID attribute for authenticated user
                $this->user->setAttribute('id', $new_user->getId());
            } else {
                //get user from db by user_provider
                $criteria = new Criteria();
                $criteria->add(LzInternalExternalIdsPeer::ID_EXTERNAL, $user_provider_from_db->getId(), Criteria::EQUAL);

                $in_ex_from_db = LzInternalExternalIdsPeer::doSelectOne($criteria);

                $user_from_db = LzUserPeer::retrieveByPK($in_ex_from_db->getIdInternal());

                //set properties
                $user_from_db->setExpiresAt($this->getExpiresAtTime());
                $user_from_db->setIdUserProvider($user_provider_from_db->getId());

                $user_from_db->save();

                // set ID attribute for authenticated user
                $this->user->setAttribute('id', $user_from_db->getId());
            }

            /*
             * Set attributes
             */
            $this->user->setAttribute('id_user_provider', $user_provider_from_db->getId());
            $this->setAttributes();

            /*
             * Authorizing user
             */
            $this->user->setAuthenticated(true);

            /*
             * Redirecting to homepage
             */
            return $this->redirect('@homepage');
        }
    }

    public function executeLogout(sfWebRequest $request) {
        $user = $this->getUser();
        $user->setAuthenticated(false);
        $user->shutdown();
        
        return $this->redirect('@homepage');
    }

    protected function getExpiresAtTime() {
        return time() + sfConfig::get('app_LoginzaPlugin_expires_after_sec');
    }
    
    protected function setAttributes()
    {
        $this->user->setAttribute('identity', $this->loginza_response['identity']);
        $this->user->setAttribute('provider', $this->loginza_response['provider']);
        
        if(isset($this->loginza_response['name'])){
            $this->user->setAttribute('first_name', $this->loginza_response['name']['first_name']);
            $this->user->setAttribute('last_name', $this->loginza_response['name']['last_name']);
        }
        if(isset($this->loginza_response['email']))
            $this->user->setAttribute('email', $this->loginza_response['email']);
        if(isset($this->loginza_response['photo']))
            $this->user->setAttribute('photo', $this->loginza_response['photo']);
        if(isset($this->loginza_response['uid']))
            $this->user->setAttribute('uid', $this->loginza_response['uid']);
        if(isset($this->loginza_response['nickname']))
            $this->user->setAttribute('nickname', $this->loginza_response['nickname']);
        if(isset($this->loginza_response['gender']))
            $this->user->setAttribute('gender', $this->loginza_response['gender']);
        if(isset($this->loginza_response['dob']))
            $this->user->setAttribute('dob', $this->loginza_response['dob']);
        if(isset($this->loginza_response['im'])){
            $this->user->setAttribute('skype', $this->loginza_response['im']['skype']);
            $this->user->setAttribute('icq', $this->loginza_response['im']['icq']);
        }
        if(isset($this->loginza_response['biography']))
            $this->user->setAttribute('biography', $this->loginza_response['biography']);
        if(isset($this->loginza_response['work'])){
            $this->user->setAttribute('company', $this->loginza_response['work']['company']);
            $this->user->setAttribute('job', $this->loginza_response['work']['job']);
        }
        if(isset($this->loginza_response['adress'])){
            $this->user->setAttribute('home-adress', $this->loginza_response['adress']['home']);
            $this->user->setAttribute('business-adress', $this->loginza_response['adress']['business']);
        }
        if(isset($this->loginza_response['phone'])){
            $this->user->setAttribute('prefered-phone', $this->loginza_response['phone']['prefered']);
            $this->user->setAttribute('home-phone', $this->loginza_response['phone']['home']);
            $this->user->setAttribute('work-phone', $this->loginza_response['phone']['work']);
            $this->user->setAttribute('mobile-phone', $this->loginza_response['phone']['mobile']);
            $this->user->setAttribute('fax', $this->loginza_response['phone']['fax']);
        }
        if(isset($this->loginza_response['web'])){
            $this->user->setAttribute('web', $this->loginza_response['web']['default']);
            $this->user->setAttribute('blog', $this->loginza_response['web']['blog']);
        }
    }

    protected function createUserProvider() {
        $new_user_provider = new LzUserProvider();
        
        $new_user_provider->setIdentity($this->loginza_response['identity']);
        $new_user_provider->setProvider($this->loginza_response['provider']);

        if (isset($this->loginza_response['name'])) {
            $new_user_provider->setFirstName($this->loginza_response['name']['first_name']);
            $new_user_provider->setLastName($this->loginza_response['name']['last_name']);            
        }
        if (isset($this->loginza_response['uid']))
            $new_user_provider->setUid($this->loginza_response['uid']);
        if (isset($this->loginza_response['nickname']))
            $new_user_provider->setNick($this->loginza_response['nickname']);
        if (isset($this->loginza_response['email'])){
            $new_user_provider->setEmail($this->loginza_response['email']);
        }
        if (isset($this->loginza_response['gender']))
            $new_user_provider->setGender($this->loginza_response['gender']);
        if (isset($this->loginza_response['dob']))
            $new_user_provider->setBirthday($this->loginza_response['dob']);
        if (isset($this->loginza_response['im'])) {
            if (isset($this->loginza_response['im']['icq']))
                $new_user_provider->setICQ($this->loginza_response['im']['icq']);
            if (isset($this->loginza_response['im']['skype']))
                $new_user_provider->setSkype($this->loginza_response['im']['skype']);
        }
        if (isset($this->loginza_response['biography']))
            $new_user_provider->setBiography($this->loginza_response['biography']);
        if (isset($this->loginza_response['photo'])){
            $new_user_provider->setPhoto($this->loginza_response['photo']);
        }
        if (isset($this->loginza_response['work'])) {
            if (isset($this->loginza_response['work']['company']))
                $new_user_provider->setCompany($this->loginza_response['work']['company']);
            if (isset($this->loginza_response['work']['job']))
                $new_user_provider->setJob($this->loginza_response['work']['job']);
        }
        if (isset($this->loginza_response['adress'])) {
            if (isset($this->loginza_response['adress']['home']))
                $new_user_provider->setHomeAdress($this->loginza_response['adress']['home']);
            if (isset($this->loginza_response['adress']['business']))
                $new_user_provider->setBusinessAdress($this->loginza_response['adress']['business']);
        }
        if (isset($this->loginza_response['phone'])) {
            if (isset($this->loginza_response['phone']['preferred']))
                $new_user_provider->setPreferredPhone($this->loginza_response['phone']['preferred']);
            if (isset($this->loginza_response['phone']['home']))
                $new_user_provider->setHomePhone($this->loginza_response['phone']['home']);
            if (isset($this->loginza_response['phone']['work']))
                $new_user_provider->setWorkPhone($this->loginza_response['phone']['work']);
            if (isset($this->loginza_response['phone']['mobile']))
                $new_user_provider->setMobilePhone($this->loginza_response['phone']['mobile']);
            if (isset($this->loginza_response['phone']['fax']))
                $new_user_provider->setFax($this->loginza_response['phone']['fax']);
        }
        if (isset($this->loginza_response['web'])) {
            if (isset($this->loginza_response['web']['default']))
                $new_user_provider->setWeb($this->loginza_response['web']['default']);
            if (isset($this->loginza_response['web']['blog']))
                $new_user_provider->setBlog($this->loginza_response['web']['blog']);
        }

        $new_user_provider->save();

        return $new_user_provider;
    }

}
